function generateUUID() {
    var d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now(); //use high-precision timer if available
    }
    var uuid = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}

var kefu = {
	/* 如果用户已登录，这里存储的是用户的session，如果用户未登录，这里存储的是生成的 "youke+uuid" */
	token:null,
	/**
	 * 获取token，也就是 session id。获取的字符串如 f26e7b71-90e2-4913-8eb4-b32a92e43c00
	 * 如果用户未登录，那么获取到的是  youke_uuid。 这个会设置成layim 的  mine.id
	 */
	getToken:function(){
		if(this.token == null){
			this.token = localStorage.getItem('token');
		}
		if(this.token == null || this.token.length < 5){
			this.token = 'youke_'+generateUUID();
		}
		this.setToken(this.token);
		return this.token;
	},
	/**
	 * 设置token，也就是session id
	 * 格式如 f26e7b71-90e2-4913-8eb4-b32a92e43c00
	 */
	setToken:function(t){
		this.token = t;
		localStorage.setItem('token',this.token);
	},
		
}

var socket = {
	url:'ws://xxxxxx',	//websocket链接的url，在 socket.connect时传入赋值
	socket:null,
	onopen:function(){ console.log('onopen'); },	//当socket onopen 执行的function
	onmessage:function(res){ console.log('onmessage:'+res); },	//监听收到的消息的function
	
	connect:function(url){
		this.url = url;
		this.socket = new WebSocket(url);

		this.socket.onopen = function(){
			console.log(1);
			socket.onopen();
		};
		this.socket.onmessage = function(res){
			//res为接受到的值，如 {"emit": "messageName", "data": {}}
			socket.onmessage(res);
		};
	},
	//重新连接，主要用于断线重连
	reconnect:function(){
		this.connect(this.url);
	},
	
	send:function(text){
		if(this.socket.readyState == this.socket.OPEN){
			this.socket.send(text);
		}else if(this.socket.readyState == this.socket.CLOSED || this.socket.readyState == this.socket.CLOSING){
			alert('socket 已关闭，正在开启重连');
			this.reconnect();
		}
		
	}
}
